import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/music_source.dart';

/// 音质设置服务
/// 管理全局的音质选择和持久化存储
class AudioQualityService extends ChangeNotifier {
  static final AudioQualityService _instance = AudioQualityService._internal();
  factory AudioQualityService() => _instance;
  AudioQualityService._internal();

  AudioQuality _selectedQuality = AudioQuality.high;
  static const String _qualityKey = 'selected_audio_quality';

  /// 获取当前选择的音质
  AudioQuality get selectedQuality => _selectedQuality;

  /// 初始化服务，从本地存储加载音质设置
  Future<void> initialize() async {
    await _loadQualityFromStorage();
  }

  /// 设置音质
  Future<void> setQuality(AudioQuality quality) async {
    if (_selectedQuality != quality) {
      _selectedQuality = quality;
      await _saveQualityToStorage();
      notifyListeners();
    }
  }

  /// 从本地存储加载音质设置
  Future<void> _loadQualityFromStorage() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final qualityValue = prefs.getString(_qualityKey);
      if (qualityValue != null) {
        _selectedQuality = AudioQuality.fromString(qualityValue);
        notifyListeners();
      }
    } catch (e) {
      print('加载音质设置失败: $e');
      // 使用默认音质
    }
  }

  /// 保存音质设置到本地存储
  Future<void> _saveQualityToStorage() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_qualityKey, _selectedQuality.value);
    } catch (e) {
      print('保存音质设置失败: $e');
    }
  }
}